package com.webservicetest.demo.helloworld;

import com.webservicetest.demo.helloworld.util.JavaStringCompiler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.Endpoint;
import java.io.File;

@RestController
public class WebServiceCreater {

    @GetMapping("/generateWS/{servicename}/{returnstring}")
    public String generateWS(@PathVariable("servicename")String servicename,@PathVariable("returnstring")String returnstring) throws Exception {

        File directory = new File("");
//        String canonicalPath = directory.getCanonicalPath();
//        String absolutePath = directory.getAbsolutePath();

        String content = "package com.webservicetest.demo.helloworld.webserviceclass;\n" +
                "\n" +
                "import javax.jws.WebService;\n" +
                "\n" +
                "@WebService\n" +
                "public class " +
                servicename +
                " {\n" +
                "    public String sayHello(String name){\n" +
                "        return \"" +
                returnstring +
                " \" + name + \"!\";\n" +
                "    }\n" +
                "}\n";


        JavaStringCompiler compiler = new JavaStringCompiler();
        Class<?> clzMul = compiler.compile("com.webservicetest.demo.helloworld.webserviceclass." +servicename
                , content);
        WebServiceCreater webServiceCreater1 = new WebServiceCreater();
        webServiceCreater1.publish(clzMul, servicename);
        return "success:"+servicename+","+returnstring;
    }

    //动态发布接口
    private void publish(Class<?> clzMul, String serviceName) throws Exception {
//        serviceName = firstCharLower(serviceName);
        Endpoint endpoint = Endpoint.create(clzMul.newInstance());
        endpoint.publish("http://localhost:8081/listService/" + serviceName);

    }
}
